//
//  SRPersonalCenterViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/3/25.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRPersonalCenterViewController.h"
#import "SRPersonalHeaderView.h"

#import "SRPeronalCenterTableViewCell.h"
#import "UINavigationBar+Awesome.h"

#import "SRPersonalCenterConstant.h"
#import "SRPersonalCenterSectionModel.h"
#import "SRPersonalCenterModel.h"

#import "FZUserSettingViewController.h"
#import "FZLoginViewController.h"
#import "FZRegisterViewController.h"
#import "FZTextInputViewController.h"
#import "SRMessageCenterViewController.h"
#import "SRUserInfoEditViewController.h"
#import "SRWorkListViewController.h"

#import "SRCommonConstants.h"
#import "SRLoginManager.h"
#import "FZCommonShare.h"
#import "SRSchoolClassServices.h"

@interface SRPersonalCenterViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *items;
@property (strong, nonatomic) SRPersonalHeaderView *headerView;
@property (strong, nonatomic) UIView *tabbarDot;

@property (strong, nonatomic) UIView *rightView;
@property (strong, nonatomic) UIView *rightRedView;

@property (strong, nonatomic) NSString *lastMessageID;

@end

@implementation SRPersonalCenterViewController

- (void)dealloc {
    [self removeMsgNotification];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"我";
    
    [self setupData];
    [self setupView];
    [self setupNavigationBarButtonItem];
    
    [self getUserInfoFromConfig];
    [self addMsgNotification];
    [self querySystemMessage];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
    [self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:YES];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    [self.headerView resetHeaderViewWithLogin:[SRLoginManager sharedManager].hasLogin];
    
    [self querySystemMessage];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    CGFloat headerHeight = MAX(239, SCREEN_WIDTH * (239 / 375.0));//封面高度比例 + tab高度45
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, headerHeight);
    self.tableView.tableHeaderView = self.headerView;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar lt_reset];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Init

- (void)setupData {
    self.items = [@[] mutableCopy];
}

- (void)setupView {
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    self.navigationItem.titleView = [[UILabel alloc] init];
    
    self.edgesForExtendedLayout = UIRectEdgeTop | UIRectEdgeLeft | UIRectEdgeRight;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 55.0f, 0, 0);
    self.tableView.separatorColor = css.color_7;
	self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	
    self.tableView.backgroundColor = css.color_2;
    self.tableView.rowHeight = 64;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [self.tableView registerNib:[UINib nibWithNibName:kSRPeronalCenterTableViewCell bundle:nil] forCellReuseIdentifier:kSRPeronalCenterTableViewCell];
    
    [self.view addSubview:self.tableView];
    
    [self setupTableHeaderView];
    
    self.tabbarDot = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    self.tabbarDot.layer.cornerRadius = 5.0f;
    self.tabbarDot.backgroundColor = css.color_10;
    self.tabbarDot.clipsToBounds = YES;
//    NSInteger itemCount = self.tabBarController.tabBar.items.count;
    CGFloat itemWidth = self.tabBarController.tabBar.itemWidth;
//    CGFloat halfItemWidth = SCREEN_WIDTH / (itemCount * 2);
    CGFloat xOffset = itemWidth * 2.5 + self.tabBarController.tabBar.itemSpacing * 2;
    UITabBarItem *targetItem = [self.tabBarController.tabBar.items lastObject];
    CGFloat imageHalfWidth = targetItem.selectedImage.size.width / 2.0f;
    self.tabbarDot.frame = CGRectMake(xOffset + imageHalfWidth, 5.0f, 10.0f, 10.0f);
    self.tabbarDot.hidden = NO;
    [self.tabBarController.tabBar addSubview:self.tabbarDot];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.equalTo(self.view);
    }];
    
    self.view.backgroundColor = css.color_2;
}

- (void)setupNavigationBarButtonItem {
    UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setImage:[UIImage imageNamed:@"icon_message_btn"] forState:UIControlStateNormal];
    [rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    rightButton.frame = CGRectMake(0, 0, 44, 44);
    [rightButton addTarget: self action: @selector(onMessageButton:) forControlEvents: UIControlEventTouchUpInside];
    
    self.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    [self.rightView addSubview:rightButton];
    
    self.rightRedView = [[UIView alloc] initWithFrame:CGRectMake(40, 5, 10, 10)];
    self.rightRedView.clipsToBounds = YES;
    self.rightRedView.backgroundColor = [FZStyleSheet currentStyleSheet].color_10;
    self.rightRedView.layer.cornerRadius = 5;
    
    [self.rightView addSubview:self.rightRedView];
    
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightView];
    [self setRightBarButtonItem:rightBarItem];
}

- (void)setupTableHeaderView {
    NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"SRPersonalHeaderView" owner:nil options:nil];
    SRPersonalHeaderView *headerView = [nibArray firstObject];
    
    self.headerView = headerView;
    CGFloat coverImageHeight = MAX(239, SCREEN_WIDTH * (239 / 375.0));
    CGFloat headerHeight = coverImageHeight;//封面高度比例 + tab高度45
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, headerHeight);
    
    self.tableView.tableHeaderView = self.headerView;
    WEAKSELF
    self.headerView.touchEditButtonBlock = ^(void) {
        [weakSelf onUserInfoEditButton:nil];
    };
    
    self.headerView.touchIconBlock = ^(void) {
        if (![[SRLoginManager sharedManager] hasLogin]) {
            [weakSelf showLoginViewController];
        }
    };
    
    [self.headerView resetHeaderViewWithLogin:[SRLoginManager sharedManager].hasLogin];
}

#pragma mark - network

- (void)getUserInfoFromConfig {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"PersonalCenterConfig" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSArray *sectionJSONArray = jsonDictionary[@"config_data"];
    NSArray *modelArray = [MTLJSONAdapter modelsOfClass:[SRPersonalCenterSectionModel class] fromJSONArray:sectionJSONArray error:nil];
    self.items = [modelArray mutableCopy];

    [self.tableView reloadData];
}

- (void)querySystemMessage {
    
    WEAKSELF
    [SRSchoolClassServices queryLatestMessageSuccessBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        if (statusCode == kFZRequestStatusCodeSuccess) {
            NSString *messageID = responseDataObject[@"first_msgid"];
            if (!messageID || [messageID integerValue] == 0) {
                return ;
            }
            
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *lastMessageID = [userDefaults stringForKey:kLastSystemMessageID];
            if (lastMessageID && [lastMessageID isEqualToString:messageID]) {
                    //标识最新的消息，已经获取过了，不显示红点
                weakSelf.tabbarDot.hidden = YES;
                weakSelf.rightRedView.hidden = YES;
            } else {
                NSString *idString = [NSString stringWithFormat:@"%@", messageID];
                weakSelf.lastMessageID = idString;
                
//                [userDefaults setObject:idString forKey:kLastSystemMessageID];
//                [userDefaults synchronize];
                
                weakSelf.tabbarDot.hidden = NO;
                weakSelf.rightRedView.hidden = NO;
            }
            
        }
    } failureBlock:^(id responseObject, NSError *error) {
        
    }];
    
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.items count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section >= [self.items count]) {
        return 0;
    }
    SRPersonalCenterSectionModel *sectionModel = self.items[section];
    return [sectionModel.cellModels count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SRPeronalCenterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSRPeronalCenterTableViewCell forIndexPath:indexPath];
    SRPersonalCenterSectionModel *sectionModel = self.items[indexPath.section];
    if ([sectionModel.cellModels count] > indexPath.row) {
        SRPersonalCenterModel *item = [sectionModel.cellModels objectAtIndex:indexPath.row];
        [cell updateCellInfo:item];
    }
    
    return cell;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
	if (section == 0) {
		return 10;
	}
    return 0.1f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SRPersonalCenterSectionModel *sectionModel = self.items[indexPath.section];
    if ([sectionModel.cellModels count] > indexPath.row) {
        SRPersonalCenterModel *model = [sectionModel.cellModels objectAtIndex:indexPath.row];
        
        if ([model.identifier isEqualToString:pc_setting]) {
                //设置
            [self toUserSettingAction];
        }else if ([model.identifier isEqualToString:pc_feedback]) {
                // 反馈
            [self toFeebackAction];
        }
        else if ([model.identifier isEqualToString:pc_sharetofriend]){
                // 分享
            [self toShareAction];
        }
        else if ([model.identifier isEqualToString:pc_work]){
                // 作品
            [self onWorkList];
        }
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Touch Event

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    viewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:viewController animated:animated];
}


- (void)onMessageButton:(id)sender {
    if (self.lastMessageID) {
        [[NSUserDefaults standardUserDefaults] setObject:self.lastMessageID forKey:kLastSystemMessageID];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    self.tabbarDot.hidden = YES;
    self.rightRedView.hidden = YES;
    
    SRMessageCenterViewController *vc = [[SRMessageCenterViewController alloc] init];
    [self pushViewController:vc animated:YES];
}

- (void)toUserSettingAction {
    FZUserSettingViewController *vc = [[FZUserSettingViewController alloc] init];
    [self pushViewController:vc animated:YES];
}

- (void)toFeebackAction {
	FZTextInputViewController *vc = [[FZTextInputViewController alloc] init];
	vc.tipTitle = @"意见反馈";
	vc.placeholder = @"请输入你的宝贵建议，让我们改善变得完美";
    vc.maxInputTextCount = 400;
    vc.isFeedback = YES;
    
	[self pushViewController:vc animated:YES];
}

- (void)toShareAction{
    WEAKSELF
    FZCommonShareContent *shareContent = [[FZCommonShareContent alloc] init];
    shareContent.dataType = FZCommonShareContentTypeWebpage;
    shareContent.title = @"英语趣点读";
    shareContent.desc = @"这个软件比较有意思，邀你一起来看看";
    UIImage *image = [UIImage imageNamed:@"defaultUserCenterCover"];
    shareContent.thumbnailData = UIImagePNGRepresentation(image);
    
    shareContent.webpageUrl = @"http://www.baidu.com";
    
    [[FZCommonShare sharedInstance] shareFromViewController:self content:shareContent fullCompletion:^(FZCommonShareSocialSNSType socialType, FZCommonShareResponseState responseState, NSString *errorMessage) {
        if (responseState == FZCommonShareResponseStateSuccess) {
            [weakSelf showHUDHintWithText:@"分享成功"];
        } else if (responseState == FZCommonShareResponseStateNotInstalled) {
            [weakSelf showHUDHintWithText:[NSString stringWithFormat:@"您的手机不支持分享到该APP"]];
        }
    }];
}

- (void)onUserInfoEditButton:(id)sender {
    WEAKSELF
    SRUserInfoEditViewController *vc = [[SRUserInfoEditViewController alloc] init];
    vc.didChangeAvatarImageBlock = ^(UIImage *image) {
        [weakSelf.headerView setIconImage:image];
    };
    
    [self pushViewController:vc animated:YES];
}

- (void)onWorkList {
    
    if (![SRLoginManager sharedManager].hasLogin){
        [self showLoginViewController];
        return;
    }
    
    SRWorkListViewController *vc = [[SRWorkListViewController alloc] init];
    [self pushViewController:vc animated:YES];
    
}

#pragma mark - 消息通知
- (void)addMsgNotification{
        //添加通话结束通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeUserNotification:) name:SRUserLoginDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidLogoutNotification:) name:SRUserLogoutDoneNotification object:nil];
}

- (void)removeMsgNotification{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRUserLoginDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRUserLogoutDoneNotification object:nil];
}

#pragma mark - Login 

- (void)changeUserNotification:(NSNotification*)notification{
    [self resetHeaderViewWithLogin:[[SRLoginManager sharedManager] hasLogin]];
    if ([[SRLoginManager sharedManager] hasLogin]) {
        
    }
}

- (void)userDidLogoutNotification:(NSNotification *)notification {
    [self resetHeaderViewWithLogin:[[SRLoginManager sharedManager] hasLogin]];
    [self.tabbarDot setHidden:YES];
}

- (void)resetHeaderViewWithLogin:(BOOL)isLogin {
    [self.headerView resetHeaderViewWithLogin:isLogin];
    
    if (isLogin) {
     
    }
}

- (void)showLoginViewController {
//    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    [delegate setupLoginViewController];
    [[SRLoginManager sharedManager] showLoginViewSinceController:self];
    
}

@end
